﻿Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.UI
Imports DevExpress.XtraScheduler.Native
Imports System.ComponentModel
Imports SIGI.Common.CommonDefinitions
Imports SIGI.Common.BE

Public Class frmAppointment

#Region "<< -Enums- >>"
    Private Enum AptImportance
        <Description("Alta")>
        High = 1
        <Description("Normal")>
        Normal = 2
        <Description("Baja")>
        Low = 3
    End Enum
#End Region

#Region "<< -Attributes- >>"
    Private _Behavior As CRUD = CRUD.Insert
    Private _CurrentRecurrenceControl As RecurrenceControlBase = Nothing
    Private _Rinfo As RecurrenceInfo = Nothing
    Private _AptController As AppointmentFormController = Nothing
    Private _PatternCopy As Appointment = Nothing
    Private _FirstDayOfWeek As FirstDayOfWeek = FirstDayOfWeek.Monday 'Lunes se toma como primer día de la semana.
    Protected _SuspendUpdateCount As Integer = 0
    Private _AptIdOnDB As Integer = 0
#End Region

#Region "<< -Events- >>"
    Private Sub frmAppointment_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Try
            DateStart.DateTime = Date.Now
            DateEnd.DateTime = Date.Now
            TimeEditStart.EditValue = Date.Now
            TimeEditEnd.EditValue = DateAdd(DateInterval.Hour, 1, Date.Now)

            LoadAptImportances()

            If _Behavior = CRUD.Update Then
                LoadDate()
            End If
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
        Dim wHours As String = String.Empty
        Dim wDate As String = String.Empty
        Dim wDateStart As Date = Date.MinValue
        Dim wDateEnd As Date = Date.MaxValue
        Dim wAptController As AppointmentController = Nothing
        Dim wAptBE As AppointmentBE = Nothing

        Try
            If String.IsNullOrEmpty(txtSubject.Text.Trim) Then
                _MsgBox.ShowMessage("Asunto Vacío", "Ingrese el Asunto de la Cita",
                                    frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
                txtSubject.Focus()
                Return
            End If

            If String.IsNullOrEmpty(txtDescription.Text.Trim) Then
                _MsgBox.ShowMessage("Cita Vacía", "Ingrese la Descripción de la cita",
                                    frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
                txtDescription.Focus()
                Return
            End If

            'Fecha de Inicio
            wHours = Convert.ToDateTime(TimeEditStart.EditValue).TimeOfDay.ToString
            wDate = String.Format("{0} {1}", Format(DateStart.DateTime, "Short Date").ToString, wHours)
            wDateStart = Convert.ToDateTime(wDate)

            'Fecha de Fin
            wHours = Convert.ToDateTime(TimeEditEnd.EditValue).TimeOfDay.ToString
            wDate = String.Format("{0} {1}", Format(DateEnd.DateTime, "Short Date").ToString, wHours)
            wDateEnd = Convert.ToDateTime(wDate)

            If DateDiff(DateInterval.Hour, wDateStart, wDateEnd) < 0 Then
                _MsgBox.ShowMessage("Fechas Inválidas", "La fecha de fin no puede ser menor a la fecha de inicio",
                                    frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
                Return
            End If

            wAptController = New AppointmentController
            wAptBE = New AppointmentBE
            With wAptBE
                .Subject = txtSubject.Text.Trim
                .Description = txtDescription.Text.Trim
                .DateStart = wDateStart
                .DateEnd = wDateEnd
                .Importance = GetLabelId()
                .Warning = GetWariningMinutes()
            End With
            If _Behavior = CRUD.Insert Then
                'Inserta la cita en la BD                
                wAptController.Insert(wAptBE, GlobalVariables.gLoguedUser.UserName)
            ElseIf _Behavior = CRUD.Update Then
                'Actualiza la BD
                wAptBE.Id = _AptIdOnDB
                wAptController.Update(wAptBE)
            End If

            Me.Close()
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub
#End Region

#Region "<< -Methods- >>"
    Public Sub New(ByVal pScheduler_control As SchedulerControl, ByVal pApt As Appointment)
        MyBase.New()

        InitializeComponent()
        ' Create an instance of the controller.
        _AptController = New AppointmentFormController(pScheduler_control, pApt)
        _AptIdOnDB = pApt.Id

        ' Get an appointment pattern copy.
        _PatternCopy = _AptController.PrepareToRecurrenceEdit
        ' Get access to the recurrence information.
        _Rinfo = _PatternCopy.RecurrenceInfo
        ' We have to know what day is the first day of the week.
        _FirstDayOfWeek = pScheduler_control.OptionsView.FirstDayOfWeek
        InitializeControls(_FirstDayOfWeek)

        'Verifico si es una nueva cita o una existente.
        'NOTA: El Asunto nunca puede ser vacio ya que es un dato obligatorio a la hora
        'de cargar o en su defecto de modificar una cita.
        _Behavior = IIf(String.IsNullOrEmpty(pApt.Subject), CRUD.Insert, CRUD.Update)
    End Sub

    Protected Overridable Sub InitializeControls(ByVal pFirstDayOfWeek As FirstDayOfWeek)
        ' Preventing a reset of the control's settings.
        SuspendUpdate()
        ResumeUpdate()
    End Sub

    Protected Overridable Sub SuspendUpdate()
        _SuspendUpdateCount = (_SuspendUpdateCount + 1)
    End Sub

    Protected Overridable Sub ResumeUpdate()
        If (_SuspendUpdateCount > 0) Then
            _SuspendUpdateCount = (_SuspendUpdateCount - 1)
        End If
    End Sub

    Private Sub LoadAptImportances()
        cmbAptImportance.Properties.Items.Add(GenericMethods.GetEnumItemDescription(AptImportance.High))
        cmbAptImportance.Properties.Items.Add(GenericMethods.GetEnumItemDescription(AptImportance.Normal))
        cmbAptImportance.Properties.Items.Add(GenericMethods.GetEnumItemDescription(AptImportance.Low))
        cmbAptImportance.SelectedIndex = 1 'Normal
    End Sub

    'Devuelve el id del color de fondo que le corresponde
    'a la cita según su importancia.
    Private Function GetLabelId() As Integer
        Select Case cmbAptImportance.Text
            Case GenericMethods.GetEnumItemDescription(AptImportance.High)
                Return 1
            Case GenericMethods.GetEnumItemDescription(AptImportance.Normal)
                Return 11
            Case Else
                Return 12
        End Select
    End Function

    Private Sub LoadDate()
        txtSubject.Text = _AptController.Subject
        txtDescription.Text = _AptController.Description

        DateStart.EditValue = _AptController.Start
        TimeEditStart.EditValue = DateAdd(DateInterval.Hour, 2, _AptController.Start)

        DateEnd.EditValue = _AptController.End
        TimeEditEnd.EditValue = DateAdd(DateInterval.Hour, 2, _AptController.End)

        Select Case _AptController.LabelId
            Case 1      'Importante
                cmbAptImportance.SelectedIndex = 0
            Case 11     'Normal
                cmbAptImportance.SelectedIndex = 1
            Case Else   'Bajo
                cmbAptImportance.SelectedIndex = 2
        End Select
    End Sub

    Private Function GetWariningMinutes()
        If cmbWarning.Text.ToLower = "5 minutos" Then
            Return 5
        ElseIf cmbWarning.Text.ToLower = "15 minutos" Then
            Return 15
        ElseIf cmbWarning.Text.ToLower = "30 minutos" Then
            Return 30
        Else
            Return 60
        End If
    End Function
#End Region

End Class